<template>
  <el-row class="login-page">
    <!-- 左侧背景 -->
    <el-col :span="12" class="bg">
      <div class="overlay">
        <h1 class="slogan">
          探索世界
          <br />从这里启程
        </h1>
        <div class="features">
          <div class="feature-item">
            <el-icon>
              <Promotion />
            </el-icon>
            <span>全球旅行攻略</span>
          </div>
          <div class="feature-item">
            <el-icon>
              <Picture />
            </el-icon>
            <span>高清实景美图</span>
          </div>
          <div class="feature-item">
            <el-icon>
              <Flag />
            </el-icon>
            <span>专业路线规划</span>
          </div>
        </div>
      </div>
    </el-col>

    <!-- 右侧表单 -->
    <el-col :span="6" :offset="3" class="form-container">
      <div class="form-wrapper">
        <!-- 注册表单 -->
        <el-form
          v-if="isRegister"
          class="travel-form"
          ref="registerFormRef"
          :model="registerData"
          :rules="rules"
        >
          <h2 class="form-title">开启你的旅程 ✈️</h2>
          <el-form-item prop="username">
            <el-input
              v-model="registerData.username"
              placeholder="请输入用户名"
              :prefix-icon="User"
              size="large"
            >
              <template #prefix>
                <el-icon class="input-icon">
                  <User />
                </el-icon>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item prop="password">
            <el-input
              v-model="registerData.password"
              type="password"
              placeholder="请输入密码"
              :prefix-icon="Lock"
              size="large"
              show-password
            >
              <template #prefix>
                <el-icon class="input-icon">
                  <Lock />
                </el-icon>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item prop="rePassword">
            <el-input
              v-model="registerData.rePassword"
              type="password"
              placeholder="确认密码"
              :prefix-icon="Lock"
              size="large"
              show-password
            >
              <template #prefix>
                <el-icon class="input-icon">
                  <Lock />
                </el-icon>
              </template>
            </el-input>
          </el-form-item>

          <el-button class="submit-btn" type="primary" @click="handleRegister">
            <el-icon class="btn-icon">
              <EditPen />
            </el-icon>立即注册
          </el-button>

          <div class="switch-text">
            已有账号？
            <el-link type="primary" :underline="false" @click="isRegister = false">马上登录</el-link>
          </div>
        </el-form>

        <!-- 登录表单 -->
        <el-form v-else class="travel-form" ref="loginFormRef" :model="registerData" :rules="rules">
          <h2 class="form-title">欢迎回来浩好旅 🌍</h2>
          <el-form-item prop="username">
            <el-input
              v-model="registerData.username"
              placeholder="请输入用户名"
              :prefix-icon="User"
              size="large"
            >
              <template #prefix>
                <el-icon class="input-icon">
                  <User />
                </el-icon>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item prop="password">
            <el-input
              v-model="registerData.password"
              type="password"
              placeholder="请输入密码"
              :prefix-icon="Lock"
              size="large"
              show-password
            >
              <template #prefix>
                <el-icon class="input-icon">
                  <Lock />
                </el-icon>
              </template>
            </el-input>
          </el-form-item>

          <div class="remember-forgot">
            <el-checkbox>记住登录</el-checkbox>
            <el-link type="primary" :underline="false">忘记密码？</el-link>
          </div>

          <el-button class="submit-btn" type="primary" @click="handleLogin">
            <el-icon class="btn-icon">
              <Key />
            </el-icon>立即登录
          </el-button>

          <div class="switch-text">
            新用户？
            <el-link type="primary" :underline="false" @click="isRegister = true">免费注册</el-link>
          </div>
        </el-form>
      </div>
    </el-col>
  </el-row>
</template>
    
    <script setup>
import { User, Lock } from "@element-plus/icons-vue";
import { ref } from "vue";
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";
import { useTokenStore } from "@/stores/token.js";
import { userRegisterService, userLoginService } from "@/api/user.js";

// 控制注册与登录表单的显示， 默认显示登录
const isRegister = ref(false);
// 定义数据模型
const registerData = ref({
  username: "",
  password: "",
  rePassword: ""
});

// 表单引用
const registerFormRef = ref(null);
const loginFormRef = ref(null);

// 校验密码是否一致
const checkRePassword = (rule, value, callback) => {
  if (value !== registerData.value.password) {
    callback(new Error("两次密码不一致"));
  } else if (value === "") {
    callback(new Error("请再次输入密码"));
  } else {
    callback();
  }
};

// 定义表单创建规则
const rules = {
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    { min: 5, max: 16, message: "长度在5到16个字符", trigger: "blur" }
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 5, max: 16, message: "长度在5到16个字符", trigger: "blur" }
  ],
  rePassword: [{ validator: checkRePassword, trigger: "blur" }]
};

// 调用后台接口完成注册
const handleRegister = async () => {
  const form = registerFormRef.value;
  form.validate(async valid => {
    if (valid) {
      try {
        let result = await userRegisterService(registerData.value);
        console.log(result);
        ElMessage.success(result.msg ? result.msg : "注册成功");
        if (result.code === 0) {
          // 清空表单数据
          clearRegisterData();
          // 切换到登录表单
          isRegister.value = false;
        }
      } catch (error) {
        ElMessage.error("注册失败，请稍后重试");
      }
    }
  });
};

// 登陆函数
const tokenStore = useTokenStore();
// 获取路由对象
const router = useRouter();
const handleLogin = async () => {
  const form = loginFormRef.value;
  form.validate(async valid => {
    if (valid) {
      try {
        let result = await userLoginService(registerData.value);
        ElMessage.success(result.msg ? result.msg : "登录成功");
        // 把得到的token存储到pinia中
        tokenStore.setToken(result.data);
        // 跳转到首页 借助于路由完成跳转
        router.push("/");
      } catch (error) {
        ElMessage.error("登录失败，请检查用户名和密码");
      }
    }
  });
};

const clearRegisterData = () => {
  registerData.value = {
    username: "",
    password: "",
    rePassword: ""
  };
};
import {
  Promotion,
  Picture,
  Flag,
  EditPen,
  Key
} from "@element-plus/icons-vue";
</script>
    
    <style lang="scss" scoped>
.login-page {
  height: 100vh;
  background: linear-gradient(135deg, #2d4279 0%, #1a2b50 100%);

  .bg {
    background: url("@/assets/login-bg.jpg") no-repeat center/cover;
    position: relative;
    overflow: hidden;

    .overlay {
      background: rgba(0, 0, 0, 0.4);
      height: 100%;
      padding: 40px;
      color: white;

      .slogan {
        font-size: 2.5rem;
        line-height: 1.3;
        margin-top: 20vh;
        text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.3);
      }

      .features {
        margin-top: 40px;

        .feature-item {
          display: flex;
          align-items: center;
          gap: 15px;
          margin: 25px 0;
          font-size: 1.1rem;
          opacity: 0.9;

          .el-icon {
            font-size: 1.8rem;
            color: #ffd04b;
          }
        }
      }
    }
  }

  .form-container {
    display: flex;
    align-items: center;
    height: 100vh;

    .form-wrapper {
      width: 100%;
      background: rgba(255, 255, 255, 0.96);
      border-radius: 20px;
      padding: 40px 35px;
      box-shadow: 0 8px 30px rgba(0, 0, 0, 0.1);
    }

    .travel-form {
      .form-title {
        color: #2d4279;
        text-align: center;
        margin-bottom: 40px;
        font-size: 1.8rem;
      }

      .el-input {
        :deep(.el-input__wrapper) {
          background: #f8f9fc;
          border-radius: 10px;
          padding: 8px 15px;
          box-shadow: none;

          &:hover {
            box-shadow: 0 0 0 1px #a0d8ff inset;
          }
        }
      }

      .input-icon {
        color: #2d4279;
        margin-right: 8px;
      }

      .submit-btn {
        width: 100%;
        height: 45px;
        font-size: 1.1rem;
        background: linear-gradient(135deg, #2d4279, #1a2b50);
        border: none;
        border-radius: 10px;
        margin-top: 20px;
        transition: all 0.3s ease;

        &:hover {
          transform: translateY(-2px);
          box-shadow: 0 5px 15px rgba(45, 66, 121, 0.3);
        }

        .btn-icon {
          margin-right: 8px;
          transition: transform 0.3s ease;
        }

        &:hover .btn-icon {
          transform: rotate(15deg);
        }
      }

      .remember-forgot {
        display: flex;
        justify-content: space-between;
        margin: 15px 0;
      }

      .switch-text {
        text-align: center;
        margin-top: 25px;
        color: #606266;

        .el-link {
          font-weight: 500;
          margin-left: 8px;
        }
      }
    }
  }
}

@media (max-width: 768px) {
  .login-page {
    .bg {
      display: none;
    }

    .form-container {
      width: 100%;
      padding: 0 20px;

      .form-wrapper {
        padding: 30px 25px;
      }
    }
  }
}
</style>